<template>
  <div class="discussion-container">
    <!-- 帖子列表视图 -->
    <div v-if="!showDetail" class="discussion-main">
      <div class="discussion-header">
        <h2 class="gradient-text">{{ course && course.name }} 龙王讨论区</h2>
        <el-button
          type="primary"
          class="create-btn"
          @click="handleCreatePost">
          <el-icon><EditPen /></el-icon>
          发起讨论
        </el-button>
      </div>

      <!-- 帖子编辑器 -->
      <PostEditor
        v-if="showEditor"
        :courseId="courseId"
        :currentUser="userInfo"
        @post-created="handlePostCreated"
        @back="handleEditorBack"
      />

      <!-- 搜索组件 -->
      <TopicSearch
        v-if="!showEditor"
        :courseId="courseId"
        @update:posts="updatePosts"
        class="search-component"
      />

      <div class="posts-container" v-if="!showEditor">
        <el-empty
          v-if="posts.length === 0"
          description="暂无讨论"
          class="empty-state"
        />
        <el-card
          v-for="post in posts"
          :key="post.id"
          class="post-card"
          :class="{ 'hover-effect': true }"
        >
          <div class="post-content" @click="openPostDetail(post)">
            <div class="post-header">
              <div class="post-meta">
                <div class="user-info">
                  <span class="username">{{ post.user.username }}</span>
                </div>
                <span class="time">
                  <el-icon><Clock /></el-icon>
                  {{ formatTime(post.created_at) }}
                </span>
              </div>
              <el-tag
                size="small"
                :type="getTagType(post.topic)"
                effect="light"
                class="topic-tag"
              >
                {{ post.topic }}
              </el-tag>
            </div>
            <div class="post-title">
              {{ extractTitle(post.content) }}
            </div>
            <div class="post-preview">
              {{ getPreviewContent(post.content) }}
            </div>
          </div>
          <div class="post-footer">
            <div class="post-actions">
                <el-button
                  type="text"
                  class="action-btn favorite-btn"
                  :class="{ 'is-favorited': post.is_favorite }"
                   @click.stop="handleFavorite(post)"
                >
                <el-icon><Star /></el-icon>
                   收藏
                </el-button>
              <el-button
                type="text"
                class="action-btn like-btn"
                :class="{ 'liked': post.is_liked }"
                @click.stop="handleLike(post)"
              >
                <el-icon><Thumb /></el-icon>
                {{ post.likes_count }} 赞
              </el-button>
            </div>
            <el-button
              v-if="canDelete(post)"
              type="text"
              class="delete-btn action-btn"
              @click.stop="handleDelete(post)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 帖子详情视图 -->
    <PostDetail
      v-else
      :post="currentPost"
      :current-user="userInfo"
      :is-teacher="userInfo.role === 'teacher'"
      @back="closePostDetail"
      @update:post="handlePostUpdate"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, EditPen, Thumb, ArrowLeft, Delete, Star, Clock } from '@element-plus/icons-vue'
import PostDetail from "./PostDetail.vue"
import TopicSearch from "@/components/CourseDiscussion/TopicSearch.vue"
import PostEditor from "./PostEditor.vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  },
  course: {
    type: Object,
    required: true
  }
})

// 响应式状态
const posts = ref([])
const searchQuery = ref('')
const loading = ref(false)
const showDetail = ref(false)
const showEditor = ref(false)
const currentPost = ref(null)
const userInfo = ref({
  id: '',
  username: '',
  role: ''
})
//获取标签类型
const getTagType = (topic) => {
  const types = {
    '问题': 'danger',
    '分享': 'success',
    '讨论': 'warning',
    '建议': 'info'
  }
  return types[topic] || 'info'
}

// 处理编辑器返回
const handleEditorBack = () => {
  showEditor.value = false
}

// 判断是否可以删除帖子
const canDelete = (post) => {
  if (!post || !post.user || !userInfo.value) {
    return false
  }
  return userInfo.value.role === 'teacher' || post.user.id === userInfo.value.id
}

// 处理删除帖子
const handleDelete = async (post) => {
  if (!post || !post.id) {
    ElMessage.error('无效的帖子数据')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除这个帖子吗？此操作不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await axios.delete(`/backend/api/post/${post.id}/delete/`, {
      withCredentials: true
    })

    if (response && response.data && response.data.message === '删除成功') {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })

      // 如果在详情页，返回列表页
      if (showDetail.value) {
        closePostDetail()
      }

      // 从列表中移除该帖子
      posts.value = posts.value.filter(p => p.id !== post.id)
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }

    console.error('删除帖子失败:', error)
    let errorMessage = '删除失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 提取标题
const extractTitle = (content) => {
    return  content ||'无标题';
}

// 获取预览内容
const getPreviewContent = (content) => {
  return ''
}

// 处理帖子更新
const handlePostUpdate = (updatedPost) => {
  const index = posts.value.findIndex(p => p.id === updatedPost.id)
  if (index !== -1) {
    posts.value[index] = { ...updatedPost }
  }
  currentPost.value = updatedPost
}

// 打开帖子详情
const openPostDetail = async (post) => {
  loading.value = true
  try {
    // 获取帖子详情
    const response = await axios.get(`/backend/api/post/${post.id}/`, {
      withCredentials: true
    })
    currentPost.value = response.data
    showDetail.value = true
    window.scrollTo(0, 0)
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 关闭帖子详情
const closePostDetail = () => {
  showDetail.value = false
  currentPost.value = null
  // 返回列表时重新获取所有帖子
  fetchPosts()
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get('/backend/api/account/profile/', {
      withCredentials: true
    })
    if (response.status === 200) {
      userInfo.value = response.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  }
}

// 获取讨论列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/backend/api/post/course/${props.courseId}/`, {
      withCredentials: true
    })
    posts.value = response.data
  } catch (error) {
    console.error('获取讨论列表失败:', error)
    ElMessage.error('获取讨论列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 点赞/取消点赞处理函数
const handleLike = async (post) => {
  try {
    const endpoint = post.is_liked ? 'unlike' : 'like'
    const response = await axios.post(
        `/backend/api/post/${post.id}/${endpoint}/`,
        {},
        {withCredentials: true}
    )

    if (response.data.success) {
      // 更新帖子点赞数和状态
      post.likes_count = response.data.likes
      post.is_liked = !post.is_liked

      // 如果是在详情页，同时更新列表中对应的帖子
      if (showDetail.value) {
        const listPost = posts.value.find(p => p.id === post.id)
        if (listPost) {
          listPost.likes_count = response.data.likes
          listPost.is_liked = !listPost.is_liked
        }
      }

      // 显示操作成功消息
      ElMessage({
        type: 'success',
        message: post.is_liked ? '点赞成功' : '取消点赞成功',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 处理收藏
const handleFavorite = async (post) => {
  try {
    const endpoint = post.is_favorite ? 'unfavorite' : 'favorite'
    const response = await axios.post(
      `/backend/api/post/${post.id}/${endpoint}/`,
      {},
      { withCredentials: true }
    )

    if (response.data.message) {
      // 更新帖子的收藏状态
      post.is_favorite = !post.is_favorite

      ElMessage({
        type: 'success',
        message: post.is_favorite ? '收藏成功' : '取消收藏成功',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    let errorMessage = '操作失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}
// 发起讨论
const handleCreatePost = () => {
  showEditor.value = true
}

// 更新帖子列表
const updatePosts = (newPosts) => {
  posts.value = newPosts
}

// 处理帖子创建成功
const handlePostCreated = async (newPost) => {
  showEditor.value = false
  // 将新帖子添加到列表开头
  ElMessage.success('发布成功')
  await fetchPosts()
}

onMounted(() => {
  fetchPosts()
  fetchUserInfo()
})
</script>

<style scoped>
.discussion-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f9fafb;
}

.discussion-main {
  animation: fadeIn 0.3s ease-in-out;
}

.discussion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 16px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.gradient-text {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(45deg, #409EFF, #36cfc9);
  -webkit-background-clip: text;
  color: transparent;
}

.create-btn {
  padding: 12px 24px;
  font-weight: 500;
  border-radius: 8px;
  transition: transform 0.2s ease;
}

.create-btn:hover {
  transform: translateY(-2px);
}

.search-component {
  margin-bottom: 24px;
}

.posts-container {
  display: grid;
  gap: 20px;
  animation: slideUp 0.4s ease-out;
}

.post-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: white;
}

.post-card.hover-effect:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.post-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.username {
  font-weight: 600;
  font-size: 16px;
  color: #2c3e50;
}

.time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.topic-tag {
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  line-height: 1.4;
}

.post-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
  margin-bottom: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
}

.post-actions {
  display: flex;
  gap: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: #f5f7fa;
}

.like-btn {
  color: #606266;
}

.like-btn.liked {
  color: #409EFF;
}

.favorite-btn {
  color: #606266;
}

.favorite-btn.is-favorited {
  color: #f7ba2a;
}
/* 添加星星图标的样式 */
.favorite-btn.is-favorited .el-icon {
  fill: currentColor;  /* 确保图标是实心的 */
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #ff4949;
  background-color: #fef0f0;
}

.empty-state {
  padding: 48px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>